package com.zg.datapush.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zg.datapush.constant.DataPushConstants;
import com.zg.common.core.dao.datapush.dao.DpPushTaskDao;
import com.zg.common.core.dao.datapush.entity.DpPushTask;
import com.zg.datapush.service.TaskScheduleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 任务调度初始化器
 * 应用启动时自动启动已启用的定时任务
 * @author zg
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class TaskScheduleInitializer implements ApplicationRunner {

    private final DpPushTaskDao pushTaskDao;
    private final TaskScheduleService taskScheduleService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("开始初始化推送任务调度...");

        try {
            // 查询所有启用的定时任务
            List<DpPushTask> enabledTasks = pushTaskDao.list(
                new LambdaQueryWrapper<DpPushTask>()
                    .eq(DpPushTask::getStatus, DataPushConstants.TASK_STATUS_ENABLED) // 启用状态
                    .eq(DpPushTask::getScheduleType, DataPushConstants.SCHEDULE_TYPE_CRON) // 只支持定时调度
            );

            for (DpPushTask task : enabledTasks) {
                try {
                    taskScheduleService.startTaskSchedule(task.getId());
                    log.info("启动推送任务调度: {}", task.getTaskName());
                } catch (Exception e) {
                    log.error("启动推送任务调度失败: {}", task.getTaskName(), e);
                }
            }

            log.info("推送任务调度初始化完成，共启动 {} 个任务", enabledTasks.size());

        } catch (Exception e) {
            log.error("推送任务调度初始化失败", e);
        }
    }
}
